<template>
	<div 	class="users">
		<h2>学长学姐信息管理</h2>
		<div class="container">
			<div class="part1">
				<el-form
					ref="form"
					:model="formData"
					label-width="60px"
					label-position="left"
				>
					<el-form-item label="封面图">
						<el-image
							style="width: 150px; margin-right: 10px;"
							:src="formData.avatarUrl"
							fit="contain"
						/>
						<ChooseFile @change="chooseFile">
							<div class="choose-file">点击选择图片</div>
						</ChooseFile>
					</el-form-item>
					<el-form-item label="用户ID">
						<el-input v-model.number="formData.siUId" />
					</el-form-item>
					<el-form-item label="昵称">
						<el-input v-model="formData.siNickName" />
					</el-form-item>
					<el-form-item label="手机号">
						<el-input
							type="phone"
							v-model="formData.siPhone"
						/>
					</el-form-item>
					<!-- 学院 -->
					<el-form-item label="学院">
						<el-input v-model="formData.siAcademy" />
					</el-form-item>
					<!-- 方向 -->
					<el-form-item label="方向">
						<el-input v-model="formData.siOrientation" />
					</el-form-item>
					<!-- 价钱 -->
					<el-form-item label="价格">
						<el-input v-model.number="formData.siUnitPrice">
							<template slot="append">Aha币/30分钟</template>
						</el-input>
					</el-form-item>
					<!-- 自我介绍 -->
					<el-form-item label="介绍">
						<el-input
							type="textarea"
							rows="5"
							v-model="formData.siSelfIntro"
						/>
					</el-form-item>
				</el-form>
			</div>
			<div class="part2">
				<el-form
					ref="form"
					:model="formData"
					label-width="90px"
					label-position="left"
				>
					<!-- 可约时间 -->
					<el-form-item label="可约时间">
						<el-input v-model="formData.siAccessibleTime" />
					</el-form-item>
					<!-- 可约时间 -->
					<el-form-item label="具体时间">
						<el-button
							size="small"
							@click="readTime"
						>
							点击查看
						</el-button>
					</el-form-item>
					<!-- 右上角tag -->
					<el-form-item label="右上角tag">
						<el-tag
							class="tag"
							v-for="(tag,i) in formData.siPlatformTag"
							:key="tag"
							closable
							:disable-transitions="false"
							@close="removeTagCb('siPlatformTag',i)"
						>
							{{tag}}
						</el-tag>
						<el-input
							v-if="platformTagInputting"
							v-model="inputPlatformTag"
							style="width: 100px;"
							size="small"
							autofocus
							@keyup.enter.native="addTagCb('siPlatformTag')"
							@blur="addTagCb('siPlatformTag')"
						/>
						<el-button
							v-else
							size="small"
							@click="platformTagInputting=true"
						>
							添加标签
						</el-button>
					</el-form-item>
					<!-- 个人tag -->
					<el-form-item label="个人tag">
						<el-tag
							class="tag"
							v-for="(tag,i) in formData.siPersonalTag"
							:key="tag"
							closable
							:disable-transitions="false"
							@close="removeTagCb('siPersonalTag',i)"
						>
							{{tag}}
						</el-tag>
						<el-input
							v-if="personalTagInputting"
							v-model="inputPersonTag"
							style="width: 100px;"
							size="small"
							autofocus
							@keyup.enter.native="addTagCb('siPersonalTag')"
							@blur="addTagCb('siPersonalTag')"
						/>
						<el-button
							v-else
							size="small"
							@click="personalTagInputting=true"
						>
							添加标签
						</el-button>
					</el-form-item>
					<!-- 类型， 1竞赛 2深造 3就业 -->
					<el-form-item label="咨询类型">
						<el-checkbox-group v-model="formData.siType">
							<el-checkbox label="竞赛" />
							<el-checkbox label="深造" />
							<el-checkbox label="就业" />
						</el-checkbox-group>
					</el-form-item>
					<!-- 已咨询次数 -->
					<el-form-item label="咨询次数">
						{{formData.siConsultedNum}}
					</el-form-item>
					<el-form-item label="综合评分">
						<el-rate
							v-model="formData.siGrade"
							disabled
							show-score
							text-color="#ff9900"
							score-template="{value}"
						/>
					</el-form-item>
					<el-button
						class="save-btn"
						type="primary"
						@click="onclickSave"
					>
						保存
					</el-button>
				</el-form>
			</div>
		</div>
		<TimeSelect
			v-if="consultTime"
			:consultTime="consultTime"
			:alreadyAppointmentTime="alreadyAppointmentTime"
			@close="consultTime=null"
			@sure="updateConsultTime"
		/>
	</div>
</template>

<script>
import {
  getConsultUser,
  updateConsultUser,
  getLeisureTime,
  getAlreadyAppointedTime,
  putConsultTime
} from '@user/api/consult'
import { getPublicUploadSign } from '@/api/system'
import { cosUpload } from '@/utils/file'
import TimeSelect from '../components/TimeSelect.vue'
export default {
  route: {
    name: 'ConsultDetail',
    meta: {
      login: true,
      showLeft: true,
      activeName: 'Consult',
    },
  },
  components: {
    TimeSelect
  },
  data() {
    return {
      formData: {
        siId: null, // id
        siUId: null, // 用户id
        siAcademy: '', // 学院
        siAccessibleTime: '', // 可约时间
        siPhone: '', // 手机号
        siConsultedNum: 0, // 咨询次数
        siGrade: 0, // 评分        siNickName: '金隆🐟', // 昵称
        siOrientation: '', // 方向
        siPersonalTag: [], // 个人标签
        siPlatformTag: [], // 平台标签（右上角）
        siSelfIntro: '', // 自我介绍
        siType: [], // 类型 1竞赛 2深造 3就业, 用|分开
        siUnitPrice: 0, // 半小时定价
        priority: 0, // 是否置顶
        show: 0, // 是否显示
      },
      platformTagInputting: false, // 输入平台标签（小程序右上角）
      inputPlatformTag: '', // 平台标签输入内容
      personalTagInputting: false, // 输入个人标签
      inputPersonTag: '', // 个人标签内容
      consultTime: null, // 可咨询时间数组，有的时候会传入弹窗进行选择
      alreadyAppointmentTime: { 1: [], 2: [], 3: [], 4: [], 5: [], 6: [], 7: [] }, // 已约时间
    }
  },
  created() {
    this.loadConsultUser()
  },
  methods: {
    /**
		 * 加载学长学姐信息
		 */
    async loadConsultUser() {
      this.$loading()
      try {
        const siData = (await getConsultUser(this.$route.query.siId)).data

        siData.siPersonalTag = siData.siPersonalTag ? siData.siPersonalTag.trim().split('|').filter(tag => tag !== '') : []
        siData.siPlatformTag = siData.siPlatformTag ? siData.siPlatformTag.trim().split('|').filter(tag => tag !== '') : []
        siData.siSelfIntro = siData.siSelfIntro ? siData.siSelfIntro.replace(/<br>/g, '\n').replace(/&ensp;/g, ' ') : '' // 将textarea内容反格式化

        const siType = siData.siType ? siData.siType.trim().split('|').filter(tag => tag !== '') : []
        const typeMap = {
          1: '竞赛',
          2: '深造',
          3: '就业',
        }

        siData.siType = siType.map(item => typeMap[ item ])

        this.formData = siData
        console.log(this.formData)
      } catch (err) {
        console.log(err)
      }
      this.$hideLoading()
    },
    /**
		 * 选择文件, 并上传
		 */
    async chooseFile(e) {
      this.$loading()
      try {
        const sign = (await getPublicUploadSign(`avatarSenior${ Date.now() }.jpg`)).data

        this.formData.avatarUrl = await cosUpload(e[ 0 ], sign)
      } catch (err) {
        console.log(err)
      }
      this.$hideLoading()

    },
    /**
     * 添加标签回调
     */
    addTagCb(key) {
      if (key === 'siPlatformTag') {
        this.platformTagInputting = false
        this.inputPlatformTag && this.formData[ key ].push(this.inputPlatformTag)
        this.inputPlatformTag = ''
      } else if (key === 'siPersonalTag') {
        this.personalTagInputting = false
        this.inputPersonTag && this.formData[ key ].push(this.inputPersonTag)
        this.inputPersonTag = ''
      }
    },
    /**
     * 删除标签回调
     */
    removeTagCb(key, i) {
      this.formData[ key ].splice(i, 1)
    },
    /**
		 * 点击查看咨询时间
		 */
    async readTime() {
      this.$loading()
      try {
        const res = await Promise.all([
          getAlreadyAppointedTime(this.formData.siId),
          getLeisureTime(this.formData.siId)
        ])

        res[ 0 ].data.forEach(item => {
          this.alreadyAppointmentTime[ item.weekDay ].push(...item.soOrderTime.split('|').filter(item => item).map(item => +item))
        })
        this.consultTime = res[ 1 ].data
        console.log(this.alreadyAppointmentTime)
        console.log(this.consultTime)
      } catch (err) {
        console.log(err)
      }
      this.$hideLoading()
    },
    /**
		 * 更新咨询时间
		 */
    async updateConsultTime(e) {
      /* 把选中的空闲时间和已约订单时间合并 */
      // e.forEach(item => {
      //   item.sctStartTime = item.sctStartTime.split('|').filter(item => item).concat(this.alreadyAppointmentTime[ item.sctWeekDay ]).join('|')
      // })
      console.log(e)
      this.$loading()
      try {
        await putConsultTime({
          siId: this.formData.siId,
          time: e
        })
        this.$success('更新成功')
        this.consultTime = null
        this.alreadyAppointmentTime = { 1: [], 2: [], 3: [], 4: [], 5: [], 6: [], 7: [] }
      } catch (err) {
        console.log(err)
      }
      this.$hideLoading()
    },
    /**
		 * 点击保存
		 */
    async onclickSave() {
      this.$loading()
      try {
        /* siType值转化 */
        const typeMap = {
          '竞赛': 1,
          '深造': 2,
          '就业': 3,
        }
        const siType = this.formData.siType.map(item => typeMap[ item ])

        await updateConsultUser({
          ...this.formData,
          siSelfIntro: this.formData.siSelfIntro.replace(/\n/g, '<br>').replace(/ /g, '&ensp;'), // 将textarea内容格式化
          siPlatformTag: this.formData.siPlatformTag.join('|'),
          siPersonalTag: this.formData.siPersonalTag.join('|'),
          siType: siType.join('|'),
        })
        this.$success('保存成功')
      } catch (err) {
        console.log(err)
      }
      this.$hideLoading()
    }
  }
}
</script>

<style lang="scss" scoped>
.users {
  position: relative;
  min-width: 800px;
  padding: 20px;

  h2 {
    margin-bottom: 10px;
    color: $blue;
  }

  .container {
    display: grid;
    grid-template-columns: 1fr 1fr;
    grid-gap: 20px;

    .choose-file {
      font-weight: bold;
      cursor: pointer;
    }

    .tag {
      margin-right: 8px;
    }

    .save-btn {
      width: 100%;
    }
  }
}
</style>
